package _11_整理题目._3_字符串_递归_dfs_bfs_双指针._矩阵搜索;

import java.util.Arrays;

/**
 *
 *
 */
public class _31_矩阵中严格递增的的路径数 {

    final int MOD = (int)1e9 + 7;
    final int[][] dirs = {{0,-1}, {0, 1}, {-1, 0}, {1, 0}};
    int[][] grid, f;
    int m, n;

    public int countPaths(int[][] grid) {
        this.m = grid.length;
        this.n = grid[0].length;
        this.grid = grid;
        f = new int[m][n];
        for (int i = 0; i < m; i++) {
            Arrays.fill(f[i], -1);
        }
        int ans = 1;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                ans = (ans + dfs(i, j)) % MOD;
            }
        }
        return ans;
    }

    public int dfs(int i, int j) {
        if (f[i][j] != -1) return f[i][j];
        int count = 1;
        for (int[] dir : dirs) {
            int x = i + dir[0];
            int y = j + dir[1];
            if (x>=0 && x<m && y>=0 && y<n && grid[i][j]<grid[x][y]) {
                count = (count + dfs(x, y)) % MOD;
            }
        }
        f[i][j] = count;
        return f[i][j];
    }
}
